Introduction to Machine Learning

Unit 25: Evaluation (Contd) + DBSCAN

1. Introduction

This unit continues the evaluation story from Unit 24, now introducing extrinsic clustering evaluation measures — Purity, the Rand Index, and the Jaccard Coefficient — then switches to a fundamentally different clustering algorithm: DBSCAN. We will see how DBSCAN discovers clusters of arbitrary shape and explicitly flags noise/outlier points, and we will study how to select its hyperparameters MinPts and \( \varepsilon \) (epsilon) via the K-distance graph.

Learning Objectives

Today's Agenda

  1. Recap of Silhouette Coefficient & average silhouette width
  2. Extrinsic measures: Purity, Rand Statistic (RI), Jaccard Coefficient
  3. DBSCAN algorithm & its point taxonomy
  4. Definitions: directly density-reachable, density-reachable, density-connected
  5. Identifying optimal ε and MinPts: rule-of-thumb & K-distance graph / elbow
  6. K-distance graph example on Iris dataset
  7. DBSCAN vs K-Means comparison

2. Theory

2.1 Silhouette Recap (from Unit 24)

For each object \( d_i \in C_i \), compute its per-cluster average silhouette width: \[ \bar{s}(C_j) = \frac{1}{|C_j|} \sum_{d_i \in C_j} s(i) \] and the global average silhouette width: \[ \text{ASW} = \frac{1}{n} \sum_{i=1}^{n} s(i) \] Computationally, silhouette is expensive for large datasets (O(n²) distance evaluations).

2.2 Extrinsic Clustering Evaluation Measures

Extrinsic measures require ground-truth labels and compare a generated clustering against these labels. They enable head-to-head comparison of algorithms on benchmark datasets where labels exist. We cover three: Purity, Rand Index, Jaccard.

Purity
Rand Index (RI)
Jaccard Coefficient

Intuition: For each cluster, count the frequency of the most common true class inside it. Sum these maxima and divide by n.

\[ \text{Purity} = \frac{1}{n} \sum_{i=1}^{K} \max_{j} \; |C_i \cap L_j| \]

where \( C_i \) = i-th produced cluster, \( L_j \) = j-th ground-truth label class.

Intuition: Over ALL pairs of points in the dataset, count whether clustering and ground truth AGREE on whether they belong together.

For any pair of distinct points (p, q):

\[ \text{Rand Index} = \frac{\text{TP} + \text{TN}}{\text{TP} + \text{TN} + \text{FP} + \text{FN}} \]

Range [0, 1]. Higher = more agreement. Dominated by TN when data is imbalanced (most pairs belong to different classes). Adjusted Rand Index (ARI) corrects for chance and is preferred in practice.

Intuition: Set-based overlap that IGNORS true negatives — only cares about pairs that at least one method puts together.

\[ \text{Jaccard Coefficient} = \frac{\text{TP}}{\text{TP} + \text{FP} + \text{FN}} \]

Useful when "not together" is the common case (e.g., most doc pairs should not share a topic). TN drops out entirely. Range [0, 1], higher better.

2.3 Purity Contingency Table Example

6 clusters × 6 ground-truth labels on a news-like dataset (3,204 documents):

Cluster Entertainment Financial Foreign Metro National Sports Total
135405069627677
24728029392361
311174671685
4101623119732369
5331225701323464
65358122124813648
Total (label counts)3545553419432737383,204 = n

For each cluster row, take the maximum and divide by n:

\[ \max(\text{row }1) = 506,\; \max(\text{row }2)=280,\; \max(\text{row }3)=671 \] \[ \max(\text{row }4)=162,\; \max(\text{row }5)=331,\; \max(\text{row }6)=358 \] \[ \text{Sum of maxima} = 506 + 280 + 671 + 162 + 331 + 358 = 2{,}308 \] \[ \text{Purity} = \frac{2{,}308}{3{,}204} \approx 0.720 \quad (72.0\%) \]

2.4 Rand Index Calculation: 5-Point Worked Example

Five data points: p1, p2, p3, p4, p5.
Produced clustering: C1 = {p1, p2, p3}, C2 = {p4, p5} (two clusters).
True labels: L1 = {p1, p2}, L2 = {p3, p4, p5} (two classes).

Total pairs of distinct points: C(5,2) = 10 pairs.

PairCluster together?Label together?Type
(p1,p2)Yes (C1)Yes (L1)TP
(p1,p3)Yes (C1)No (L1, L2)FP
(p1,p4)No (C1, C2)No (L1, L2)TN
(p1,p5)No (C1, C2)No (L1, L2)TN
(p2,p3)Yes (C1)No (L1, L2)FP
(p2,p4)No (C1, C2)No (L1, L2)TN
(p2,p5)No (C1, C2)No (L1, L2)TN
(p3,p4)No (C1, C2)Yes (L2)FN
(p3,p5)No (C1, C2)Yes (L2)FN
(p4,p5)Yes (C2)Yes (L2)TP

Counts: TP = 2, TN = 5, FP = 2, FN = 1. Total 10.

\[ \text{Rand Index} = \frac{2 + 5}{2 + 5 + 2 + 1} = \frac{7}{10} = 0.70 \] \[ \text{Jaccard} = \frac{2}{2 + 2 + 1} = \frac{2}{5} = 0.40 \]

2.5 DBSCAN — Density-Based Spatial Clustering of Applications with Noise

DBSCAN classifies every data point into exactly one of three categories, based on two hyperparameters: the radius ε (epsilon) and the neighbor count MinPts.

1. Core Points
2. Border Points
3. Noise Points

A point q is a core point if its ε-neighborhood contains at least MinPts points (counting q itself).

Property: Core points lie in the interior of a dense region. They are the "seeds" from which clusters are grown.

A point p is a border point if its own ε-neighborhood has < MinPts, BUT there exists a chain of direct density-reachability links from a core point to p.

Property: Border points sit on the edge of a dense region. They belong to a cluster but cannot extend it further.

A point is a noise point (outlier) if it is neither a core point nor reachable from any core point.

Property: Noise points are explicitly assigned a cluster label of −1 in sklearn. This is the only one of the three algorithms studied that allows "not in any cluster."

DBSCAN: Three Point Types A visual explanation of DBSCAN showing core points, a border point, noise, and epsilon neighborhoods for two core points. DBSCAN: three point types MinPts = 4 · ε neighborhoods shown as dashed circles ε C1 Border point Inside ε of core C1, but its neighborhood contains fewer than 4 points. Noise Not core or reachable ε C2 Outlier · label −1 Not a core point and not reachable Core point Border point Noise Outlier

2.6 DBSCAN Key Definitions

  1. Directly density-reachable: p is directly density-reachable from q if:
    • q is a core point, AND
    • p is within ε of q (p ∈ N_ε(q)).
    Note: "directly reachable" is NOT symmetric. A core can reach a border, but a border cannot reach back because borders aren't core points.
  2. Density-reachable: p is density-reachable from q if there exists a chain of points q → q₁ → q₂ → … → q_k → p such that each adjacent step is directly density-reachable. Still asymmetric in general.
  3. Density-connected: p and q are density-connected if there exists some core point o such that BOTH p and q are density-reachable from o. Symmetric! Captures the "same cluster" relationship.
  4. A DBSCAN cluster: A maximal set of density-connected points.
Density-reachability chain A density-reachability chain from core A through intermediate points and core C to border point D, showing directional reachability and shared cluster membership. DENSITY-REACHABILITY CHAIN ε radius drawn around each point DIRECT DENSITY-REACHABILITY directly directly directly directly core A core point core C core point border D not a core point ε-neighborhood ε-neighborhood ↗ Self-reachability A is density-reachable from A — trivially. A → A → Forward reachability D is density-reachable from A via A → … → C → D. A → … → D × No back-link A is not density-reachable from D: D is not core. D ↛ A SAME CLUSTER A and D are density-connected via a shared core o = A. A ≡ D

2.7 DBSCAN Example 1: Manual Execution

5 2D points: A(1,4), B(2,3), C(1,5), D(5,5), E(8,1).
MinPts = 2, ε = 2 (Euclidean distance used).

Step 0: Find cores. For each point, count its ε-neighbors (distance ≤ 2):

Step 1: Grow clusters from cores.

  1. Start with core A → Create Cluster 1. Add A. Expand to B (directly reachable) and C (directly reachable). Done (B and C, while cores, have no new points within ε).
  2. D has no other neighbors besides itself → mark as noise.
  3. E has no other neighbors besides itself → mark as noise.
PointCoordinatesTypeFinal Label
A(1, 4)CoreCluster 1
B(2, 3)CoreCluster 1
C(1, 5)CoreCluster 1
D(5, 5)Noise−1 (noise)
E(8, 1)Noise−1 (noise)

2.8 Selecting DBSCAN Hyperparameters

Selecting MinPts

Selecting ε via the K-Distance Graph

For each point in the dataset, compute the distance to its k-th nearest neighbor, with k = MinPts (or k = MinPts − 1 depending on convention). Then sort all these k-distances in ASCENDING order and plot. Use the elbow of this curve as ε.

K-distance graph for k equals 3 Sorted third-nearest-neighbor distances plotted against point index, showing an elbow near epsilon equals 0.8 and increasing distances for outliers. K-distance graph (k = 3) Sorted 3rd-nearest-neighbor distances versus point index ε ≈ 0.8 0.0 0.5 1.0 1.5 2.0 2.5 3.0 distance sorted point index → ELBOW ≈ 0.8 pick ε ≈ 0.8 points in dense clusters transition outliers (noise) large k-distance

Iris K-distance Graph Case Study

2.9 DBSCAN vs K-Means: Side-by-Side

AspectK-MeansDBSCAN
Requires K specified beforehand?YesNo (discovers K automatically from density structure)
Assumes spherical / convex clusters?Yes (centroid + SSE)No (finds arbitrarily shaped clusters — even nested / crescent shapes)
Sensitive to outliers?Very (outliers pull centroids toward them)Robust (explicitly marks outliers as noise / −1)
Forces every point into a cluster?Yes (hard assignment)No (points can remain as noise)
Struggles with arbitrary / non-convex shapes?Yes (splits them unnaturally)Excellent at non-convex and nested shapes
Memory usageLowNeeds distance matrix or spatial index (can be high)
Speed / ScalabilityVery fast (linear in n × iter)Slower (range queries needed)
Interpretable cluster centers?Yes (centroids are meaningful)No real "center" (harder to explain to business stakeholders)

3. Interactive Examples

Example 1: Purity of "one cluster per point"

A student claims "I can always achieve perfect purity, regardless of the dataset." Is this possible? If yes, construct it. If not, explain.

Yes, trivially: set K = n (each point its own singleton cluster).

In each singleton cluster, the single point has exactly one true label, so max_j |C_i ∩ L_j| = 1 for every cluster. Sum of maxima = n, so Purity = n/n = 1. This is precisely why purity alone is misleading: it rewards you for infinite K. Always use it in combination with Adjusted Rand Index, Silhouette, or metrics that penalize more clusters.

Example 2: DBSCAN MinPts Intuition

A 7-dimensional dataset is to be clustered with DBSCAN. Which MinPts value is the most reasonable starting point: 1, 2, 4, or 100?

Reveal Answer

MinPts = 4. The rule of thumb: MinPts ≥ d+1 = 8, but 4 is close and a standard starting value (MinPts ≥ 4 or 5 for high dim). Why not the others?

  • MinPts = 1: every point is its own "core" → degenerate; every point forms its own cluster / no structure.
  • MinPts = 2: borderline; very sensitive to noise.
  • MinPts = 100: too large — many truly dense regions will have fewer than 100 neighbors within any reasonable ε → everything becomes noise.

Example 3: K-Means vs DBSCAN on two moons

The classic "two interleaved half-moons" dataset has two non-convex crescent-shaped clusters. Which algorithm will recover the two moons correctly, and why?

DBSCAN will recover the two moons perfectly (with appropriate MinPts and ε):

  • Each crescent is a uniformly dense region → within each moon, every interior point is a core; the entire crescent is density-connected.
  • Between the two crescents there's a gap → no density bridge → DBSCAN correctly separates them into two clusters.

K-Means with K=2 will fail: it splits each crescent through the middle and produces two "half-moon sliced" clusters, because the centroids migrate to the overall arithmetic means of each half of the plane, which don't respect the shape.

Example 4: Rand Index edge case — perfect clustering

True labels: 4 points form 2 natural classes. Clustering produced also 2 clusters identical to the true classes. What is the Rand Index? (Compute explicitly.)

Reveal Answer

Points: p1,p2 in L1; p3,p4 in L2. Same for clusters C1={p1,p2}, C2={p3,p4}.

6 pairs:

PairClustered together?Label together?Type
(1,2)YesYesTP
(1,3)NoNoTN
(1,4)NoNoTN
(2,3)NoNoTN
(2,4)NoNoTN
(3,4)YesYesTP

TP=2, TN=4, FP=0, FN=0.

\[ \text{Rand Index} = \frac{2+4}{2+4+0+0} = 1.00 \]

As expected: perfect clustering has Rand Index = 1.

4. Numerical Solutions

Problem 1: Purity from 3×2 contingency table

Contingency table (rows = produced clusters, cols = true labels):

ClusterLabel XLabel YTotal
C18210
C23710
C35510
Label total1614n = 30

Compute Purity.

📘 Step-by-Step Solution

Step 1: Per-cluster max class count.

  • C1: max(8,2) = 8
  • C2: max(3,7) = 7
  • C3: max(5,5) = 5 (ties broken arbitrarily since value is same)

Step 2: Sum of maxima = 8 + 7 + 5 = 20.

Step 3: Divide by n:

\[ \text{Purity} = \frac{20}{30} \approx 0.667 \]

Problem 2: DBSCAN class identification

Six 1D points on a number line at positions: {1, 2, 3, 6, 10, 11}. Use MinPts=3 and ε=1.2 (distance = absolute difference). Classify each point as Core / Border / Noise. Then list the clusters found.

📘 Step-by-Step Solution

Step 1: For each point, count points within ε=1.2 (including itself).

PointPosNeighbors (|x − pos| ≤ 1.2)CountCore?
p11{1,2}2 < 3No
p22{1,2,3}3 ≥ 3✅ YES CORE
p33{2,3}2 < 3No
p46{6}1 < 3No
p510{10,11}2 < 3No
p611{10,11}2 < 3No

Step 2: Find border vs noise. p2 is the only core.

  • p1 is within ε of core p2 (|1−2|=1 ≤ 1.2) → Border of the same cluster.
  • p3 is within ε of core p2 (|3−2|=1 ≤ 1.2) → Border.
  • p4: not a core AND distance to nearest core (p2) = 4 > 1.2 → no core can reach it → Noise.
  • p5: distance to p2 = 8 > 1.2 → Noise.
  • p6: distance to p2 = 9 > 1.2 → Noise.

Clusters found: One cluster: Cluster 1 = {p1, p2, p3}. Noise = {p4, p5, p6} (label -1).

Problem 3: Rand Index & Jaccard on 4 points

True labels: L1 = {a, b}, L2 = {c, d}.
Produced clustering: C1 = {a, c}, C2 = {b}, C3 = {d} (K=3 produced).

Compute TP, TN, FP, FN, then Rand Index and Jaccard.

📘 Step-by-Step Solution

6 total pairs:

PairSame cluster?Same label?Type
(a,b)No (C1 vs C2)Yes (L1)FN
(a,c)Yes (C1)No (L1 vs L2)FP
(a,d)No (C1 vs C3)No (L1 vs L2)TN
(b,c)No (C2 vs C1)No (L1 vs L2)TN
(b,d)No (C2 vs C3)No (L1 vs L2)TN
(c,d)No (C1 vs C3)Yes (L2)FN

Counts: TP=0, TN=3, FP=1, FN=2. Total = 6.

\[ \text{Rand Index} = \frac{0 + 3}{0 + 3 + 1 + 2} = \frac{3}{6} = 0.5 \] \[ \text{Jaccard} = \frac{0}{0 + 1 + 2} = 0 \]

Interpretation: Rand 0.5 is essentially random-level agreement on this tiny dataset. Jaccard 0 because the produced clustering put no pair together that should have been together.

5. Try It Yourself

Practice 1: Purity calculation 2×3

Contingency table (clusters × labels):

RedGreenBlueTotal
Cluster A91111
Cluster B18514
Total109625

Compute Purity. Round to 3 decimals.

Max row A = max(9,1,1) = 9.

Max row B = max(1,8,5) = 8.

Sum = 17. n = 25.

\[ \text{Purity} = \frac{17}{25} = 0.680 \]
Practice 2: DBSCAN MinPts=4

2D points: A(0,0), B(1,0), C(0,1), D(1,1), E(5,5). ε=1.5, MinPts=4. Classify each point and describe resulting clusters.

ε-radius around each point:

  • A: N includes A,B,C,D (distances: 0, 1, 1, √2 ≈ 1.41 ≤ 1.5) → 4 points ≥ 4 → Core.
  • B: neighbors: A, B, D, C (same distances) → 4 → Core.
  • C: neighbors: A, C, D, B (same) → 4 → Core.
  • D: neighbors: A, B, C, D → 4 → Core.
  • E(5,5): distance to nearest others is √((5−1)²+(5−1)²) ≈ 5.66 > 1.5 → only itself in ε-neighborhood. NOT core. Not reachable from any core. → Noise.

Result: One cluster = {A,B,C,D}. E is noise (−1).

Practice 3: Adjusted Rand intuition via Rand baseline

We'll skip the exact ARI formula in this course, but explain qualitatively: If RI = 0.86 on a dataset, why might the Adjusted Rand Index ARI be only 0.58, and why do we prefer the adjusted version?

The plain Rand Index is dominated by TN (pairs that both methods put in different groups). In typical datasets with many classes, MOST pairs are in different true classes, and MOST pairs are also in different clusters — so even random clusterings can have a high Rand index merely by "mostly saying no."

The Adjusted Rand Index (ARI) corrects this by subtracting the expected RI under a random-partition baseline and normalizing, so that ARI ≈ 0 for random independent partitions and ARI = 1 only for perfect agreement. This is why ARI (and not plain RI) is the standard in scikit-learn's adjusted_rand_score.

6. Interactive Quiz

Your score: 0 / 5

7. Key Takeaways

  1. Purity = 1/n Σ max_j |C_i ∩ L_j|, but it improves monotonically with K — not a standalone metric.
  2. Rand Index = (TP + TN) / (all C(n,2) pairs) measures pairwise agreement between clustering and labels. Jaccard = TP/(TP+FP+FN) ignores TN and emphasizes positive agreement.
  3. DBSCAN has 3 point types: Core (≥ MinPts in ε-ball), Border (in a core's ε-ball but not a core), Noise (−1, everything else).
  4. DBSCAN key relationships: directly density-reachable (core→within ε), density-reachable (chain of direct), density-connected (mutually reachable from some core, symmetric → defines cluster).
  5. Set MinPts ≥ d+1 (typically 4 or 5). Set ε from the elbow of the sorted k-distance (k ≈ MinPts) curve where dense regions transition to sparse outliers.
  6. DBSCAN auto-discovers K, handles arbitrary shapes and marks outliers explicitly; K-Means requires K, assumes spherical clusters, and forces every point into a cluster.

8. Common Pitfalls

  1. Purity as the sole metric: K=n always gives Purity=1. Always cross-check with RI/ARI and silhouette or run at a fixed K chosen via domain constraints.
  2. Forgetting to count the point ITSELF in MinPts: "ε-neighborhood size ≥ MinPts" includes the query point. A point with 2 other neighbors within ε counts MinPts=3, not 2.
  3. Misunderstanding "directly density-reachable" as symmetric: It's not. A border point is within ε of a core (core→border is "direct"), but the reverse step is invalid because the border is not itself a core.
  4. Running DBSCAN on unscaled data: ε is a Euclidean radius, so feature scales matter. StandardScaler / MinMaxScaler first.
  5. Picking ε too small / too large: Too small → almost everything is noise (−1); too large → all dense points merge into one giant cluster. Use the K-distance elbow, never guess.
  6. Rand Index dominance by TNs: With many classes, TN dominates RI, making random-looking splits score high anyway. Prefer ARI.

9. Resources